<?php
namespace Home\Controller;
use Think\Controller;
class CommentController extends Controller {
    public function add(){
//        dump($_POST);die();
        if(!D('User')->checklogin()) return $this->error('请先登录',U('User/login'),1);
        if(IS_POST){
            $self_url=$_SERVER['HTTP_REFERER'];
            $id=explode(".",end(explode("/",$self_url)))['0'];
            $comment['article_id']=$_POST['article_id'];
            $commenter=D('User')->getUserByUsername($_SESSION['uid']);
            $comment['from_id']=$commenter[0]['id'];
            $comment['to_id']=$_POST['to_id'];
            $comment['to_type']=$_POST['to_type'];
            $comment['content']=$_POST['content'];
            $turnWebNotice=$comment['to_type']=='user'?'回复':'评论';
            $comment_id=D('Comment')->data($comment)->add();
            if($comment_id){
                $notice['from_id']=$comment['from_id'];
                $notice['notice_type']='comment';
                $notice['to_id']=$comment['to_id'];
                $notice['notice_id']=$comment_id;
                if(!D('Notice')->data($notice)->add()){
                    D('Comment')->deleteCommentById($comment_id);
                    return $this->error("{$turnWebNotice}失败",U('Article/detail',array('id'=>$id)),1);
                }else{
                    return $this->error("{$turnWebNotice}成功",U('Article/detail',array('id'=>$id)),1);
                }
            }
        }
        return $this->error("非法表单请求",U('Article/detail',array('id'=>$id)),1);
    }

    public function edit()
    {
        if(!D('User')->checklogin()) return $this->error('请先登录',U('User/login'),1);
        //必须先判断是为文章所有者或者root
        //if(){}
        $self_url = $_SERVER['HTTP_REFERER'];
        $id = explode(".", end(explode("/", $self_url)))['0'];
        $comment['id'] = $_POST['comment_id'];
        $comment['content'] = $_POST['comment_content'];
        $comment_id = D('Comment')->updateCommentById($comment['id'], $comment);
        return $this->success('更新成功', U('Article/detail', array('id' => $id)), 1);
    }

    public function delete()
    {
        if(!D('User')->checklogin()) return $this->error('请先登录',U('User/login'),1);
        //必须先判断是为评论所有者或者root
        //if(){}
        $self_url = $_SERVER['HTTP_REFERER'];
        $id = explode(".", end(explode("/", $self_url)))['0'];
        $comment['id'] = $_POST['comment_id'];
//        dump($comment);die();
        D('Comment')->deleteCommentById($comment['id']);
        D('Notice')->deleteNoticeByCommentId($comment['id']);
        return $this->success('删除成功', U('Article/detail', array('id' => $id)), 1);
    }
}